import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpStatus,
  ServiceUnavailableException,
} from '@nestjs/common';
import { Request, Response } from 'express';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: Error, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();

    // 非 HTTP 标准异常处理
    const rst = new ServiceUnavailableException().getResponse();
    let message: string;
    if (typeof rst === 'string') {
      message = rst;
    } else if (
      typeof rst === 'object' &&
      rst !== null &&
      'message' in rst &&
      typeof (rst as { message?: unknown }).message === 'string'
    ) {
      message = (rst as { message: string }).message;
    } else {
      message = 'Service Unavailable';
    }
    response.status(HttpStatus.SERVICE_UNAVAILABLE).json({
      statusCOde: HttpStatus.SERVICE_UNAVAILABLE,
      timestamp: new Date().toISOString(),
      path: request.url,
      message,
    });
  }
}
